import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'
import store from '@/store'

import Home from '@/views/Home'
import Search from '@/views/Search'
import Login from '@/views/Login'
import Trade from '@/views/Trade'
import Center from '@/views/Center'
import Pay from '@/views/Pay'
import PaySuccess from '@/views/PaySuccess'
import Register from '@/views/Register'
import ShopCart from '@/views/ShopCart'
import Detail from '@/views/Detail'
import AddCartSuccess from '@/views/AddCartSuccess'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  // 跳转页面时滚动条在最上面，也就是默认显示页面上面
  scrollBehavior() {
    return {
      x: 0,
      y: 0
    }
  },
  routes: [
    {
      path: '/',
      redirect: '/home'
      // 重定向
    },
    {
      path: '/home',
      name: 'Home',
      component: Home
    },
    {
      path: '/search',
      name: 'Search',
      component: Search
    },
    {
      path: '/pay',
      name: 'Pay',
      component: Pay
    },
    {
      path: '/paySuccess',
      name: 'PaySuccess',
      component: PaySuccess
    },
    {
      path: '/center',
      name: 'Center',
      component: Center
    },
    {
      path: '/trade',
      name: 'Trade',
      component: Trade
    },
    {
      path: '/addCartSuccess',
      name: 'AddCartSuccess',
      component: AddCartSuccess
    },
    {
      path: '/shopcart',
      name: 'ShopCart',
      component: ShopCart
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        isHiddenFooter: true
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
      meta: {
        isHiddenFooter: true
      }
    },
    {
      path: '/detail/:id',
      name: 'Detail',
      component: Detail
    }
  ]
})

// 需要登录才能访问的路由地址
const authList = ['/center', '/trade', '/pay', '/paysuccess', '/shopcart']

// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  const token = store.state.userInfo.token

  if (token) {
    // 登录了
    if (to.path === '/login') {
      // 登录后如果还访问登录，就跳转到首页
      next('/')
    } else {
      // 其他页面都放行
      next()
    }
  } else {
    // 没有登录
    if (authList.includes(to.path)) {
      // 没有登录，不能访问authList中的路径，要先登录
      Message.error('请先登录，在访问')
      // 去登录页面，并将要去的路径存储到参数中
      next(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  }
})

// 添加全局路由后置导航守卫
/* router.afterEach((to, from) => {
  console.log(to, from)
}) */

// 导出
export default router
